package com.lipuwater.agent.ui.dialog;

import android.Manifest;
import android.app.Dialog;
import android.app.DownloadManager;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.database.Cursor;
import android.net.Uri;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.provider.Settings;
import android.support.v7.app.AlertDialog;
import android.util.DisplayMetrics;
import android.view.KeyEvent;
import android.view.View;
import android.view.WindowManager;

import com.ismartlib.framework.permissions.Permission;
import com.ismartlib.framework.permissions.PermissionsResult;
import com.ismartlib.framework.permissions.ResultCallBack;
import com.ismartlib.ui.view.progress.NumberProgressBar;
import com.ismartlib.utils.ActivityList;
import com.ismartlib.utils.DisplayUtil;
import com.lipuwater.agent.R;
import com.lipuwater.agent.utils.ThreadUtils;

import java.io.File;

import mehdi.sakout.fancybuttons.FancyButton;

import static android.content.Context.DOWNLOAD_SERVICE;

/**
 * 　　　┏┓　　　┏┓
 * 　　┏┛┻━━━┛┻┓
 * 　　┃　　　　　　　┃
 * 　　┃　　　━　　　┃
 * 　　┃　┳┛　┗┳　┃
 * 　　┃　　　　　　　┃
 * 　　┃　　　┻　　　┃
 * 　　┃　　　　　　　┃
 * 　　┗━┓　　　┏━┛
 * 　　　　┃　　　┃神兽保佑
 * 　　　　┃　　　┃永无BUG！
 * 　　　　┃　　　┗━━━┓
 * 　　　　┃　　　　　　　┣┓
 * 　　　　┃　　　　　　　┏┛
 * 　　　　┗┓┓┏━┳┓┏┛
 * 　　　　　┃┫┫　┃┫┫
 * 　　　　　┗┻┛　┗┻┛
 * ━━━━━━神兽出没━━━━━━
 * Created by  Administrator  on 2017/6/7.
 * Email:924686754@qq.com
 */
public class DownLoadProgressDialog extends Dialog {
    private String mUrl, mFilePath, mApkName;
    private Context mContext;
    private NumberProgressBar mNumberProgressBar = null;
    private FancyButton btn;
    private callback mCallback;

    private DownloadManager mDownloadManager;
    private DownloadManager.Query mDownLoadQuery;
    private long mDownloadId;
    private int mDownProgress;

    public DownLoadProgressDialog(Context context, String url, String filePath, String apkName, callback callback) {
        super(context, R.style.MyDialogStyle);
        this.mContext = context;
        this.mUrl = url;
        this.mFilePath = filePath;
        this.mApkName = apkName;
        this.mCallback = callback;

    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.dialog_download_progress);
        init();
        requestPermission();
    }

    private void requestPermission() {
        Permission.getInstance(mContext)
                .requestPermission(Manifest.permission.WRITE_EXTERNAL_STORAGE)
                .results(new ResultCallBack() {
                    @Override
                    public void result(PermissionsResult result) {
                        if (result.getPermission().equals(Manifest.permission.WRITE_EXTERNAL_STORAGE) && result.isGranted()) {
                            downloadApk(mUrl, mFilePath);
                        } else {
                            btn.setText("重新下载");
                            new AlertDialog.Builder(mContext).
                                    setTitle("帮助")
                                    .setMessage("请在设置->应用管理->力浦净水->权限管理->读写手机存储\n避免影响正常功能的使用")
                                    .setPositiveButton("设置", new OnClickListener() {
                                        @Override
                                        public void onClick(DialogInterface dialog, int which) {
                                            Uri packageURI = Uri.parse("package:" + mContext.getPackageName());
                                            Intent intent = new Intent(Settings.ACTION_APPLICATION_DETAILS_SETTINGS, packageURI);
                                            mContext.startActivity(intent);
                                        }
                                    }).setNegativeButton("取消", null).show();
                        }
                    }
                });
    }

    private void init() {
        mNumberProgressBar = (NumberProgressBar) findViewById(R.id.progressbar);
        btn = (FancyButton) findViewById(R.id.btn);
        btn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                if (btn.getText().toString().equals("取消下载")) {
                    if (mDownloadManager != null) {
                        mDownloadManager.remove(mDownloadId);
                    }
                    ActivityList.getInstance().exit();
                } else if (btn.getText().toString().equals("点击安装")) {
                    if (mCallback != null) {
                        mCallback.onResults(true);
                    }
                } else if (btn.getText().toString().equals("重新下载")) {
                    requestPermission();
                }
            }
        });
        setCanceledOnTouchOutside(false);
        setOnKeyListener(new OnKeyListener() {
            @Override
            public boolean onKey(DialogInterface dialog, int keyCode,
                                 KeyEvent event) {
                if (keyCode == KeyEvent.KEYCODE_BACK
                        && event.getRepeatCount() == 0) {
                    return true;
                } else {
                    return false;
                }
            }
        });
        getWindow().setLayout(DisplayUtil.getScreenWidth(mContext) - dpToPx(30, mContext), WindowManager.LayoutParams.WRAP_CONTENT);
    }

    private Handler handler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            if (msg.arg1 == 100) {
                btn.setText("点击安装");
            }
            mNumberProgressBar.setProgress(msg.arg1);
        }
    };

    private void downloadApk(String url, String filePath) {
        //實時獲取下載進度
        ThreadUtils.getInstance().getExecutorService().execute(new Runnable() {
            @Override
            public void run() {
                while (mDownProgress < 101) {
                    try {
                        Thread.sleep(100);
                        getDownLoadProgress();
                        Message message = new Message();
                        message.arg1 = mDownProgress;
                        handler.sendMessage(message);
                        if (mDownProgress == 100) {
                            mDownProgress++;
                            if (mCallback != null) {
                                mCallback.onResults(true);
                            }
                        }
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                }
            }
        });
        if (mDownloadManager == null) {
            mDownloadManager = (DownloadManager) mContext.getSystemService(DOWNLOAD_SERVICE);
        }
        DownloadManager.Request request = new DownloadManager.Request(Uri.parse(url));
        File dir = new File(filePath);
        if (!dir.exists()) {
            dir.mkdirs();
        }
        File apk = new File(filePath, mApkName);
        if (apk.exists()) {
            apk.delete();
        }
        File file = new File(dir, mApkName);
        request.setDestinationUri(Uri.fromFile(file));
        mDownloadId = mDownloadManager.enqueue(request);
    }

    /**
     * 獲取下載進度
     *
     * @return
     */
    private int getDownLoadProgress() {
        if (mDownloadManager == null) {
            mDownloadManager = (DownloadManager) mContext.getSystemService(DOWNLOAD_SERVICE);
        }
        if (mDownLoadQuery == null) {
            mDownLoadQuery = new DownloadManager.Query().setFilterById(mDownloadId);
        }
        Cursor cursor = null;
        try {
            cursor = mDownloadManager.query(mDownLoadQuery);
            if (cursor != null && cursor.moveToFirst()) {
                //当前的下载量
                int downloadSofar = cursor.getInt(cursor.getColumnIndex(DownloadManager.COLUMN_BYTES_DOWNLOADED_SO_FAR));
                //文件总大小
                int totalBytes = cursor.getInt(
                        cursor.getColumnIndexOrThrow(
                                DownloadManager.COLUMN_TOTAL_SIZE_BYTES
                        ));
                mDownProgress = (int) (downloadSofar * 1.0f / totalBytes * 100);
            } else {
                //下載出錯
                mDownProgress = 101;
            }
        } finally {
            if (cursor != null) {
                cursor.close();
            }
        }
        return mDownProgress;
    }

    public interface callback {
        void onResults(boolean results);
    }

    private int dpToPx(int i, Context mContext) {
        DisplayMetrics displayMetrics = mContext.getResources()
                .getDisplayMetrics();
        return (int) ((i * displayMetrics.density) + 0.5);
    }
}
